<?php
require('header.php');
require('paginator.class.php');
requireAuth();
if(!isAdmin()) makeRedirect(route('index'));
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$msg = '';
if(isset($_POST['user_name'])){
	$userId = intval($_POST['user_id']);
	$user['user_name'] = cleanValue($_POST['user_name']);
	$user['user_email'] = cleanValue($_POST['user_email']);
	$user['user_role'] = cleanValue($_POST['user_role']);
	$user['user_timezone'] = cleanValue($_POST['user_timezone']);
	$user['user_password'] = md5($_POST['user_password']);
	$user['user_authorized'] = 'NO';

	$repassword = md5($_POST['repassword']);

	if($userId <= 0 && $user['user_password'] != $repassword || strlen($user['user_password']) < 6){
		$msg = "Password does not match";
	}
	elseif(strlen($user['user_name']) <  5){
		$msg = "User name must be 5 characters or more";
	}
	elseif($userId <= 0 && isUserExist($user['user_name'], $user['user_email'])){
		$msg = 'Username or email already in used.';
	}
	else{
		// update user
		if($userId > 0){
			if(trim($_POST['user_password']) == ''){
				unset($user['user_password']);
			}
			else{
				$user['user_password'] = generateSaltedPassword($_POST['user_password']);
			}
			if(updateUser($userId, $user)){
				$msg = 'User updated.';
			}
			else{
				$msg = 'Error when update user.';
			}
		}
		// add new user
		else{
			if(addUser($user)){
				$msg = 'New user added.';
			}
			else{
				$msg = 'Error when add new user.';
			}
		}
	}
}
?>
<div class="row">
	<div class="col-md-7">
			<?php
		    $offset = ($page - 1) * PAGING_LIMIT;

		    $sqlPost = "SELECT SQL_CALC_FOUND_ROWS
				u.*, COUNT(DISTINCT pp.post_id) AS total_pp,
				COUNT(DISTINCT gp.post_id) AS total_gp
				FROM
					users u
				LEFT JOIN page_post pp ON (u.user_id = pp.user_id)
				LEFT JOIN group_post gp ON (u.user_id = gp.user_id)
				GROUP BY
				u.user_id ORDER BY user_id DESC LIMIT $offset, " . PAGING_LIMIT;
		    $rsPost = mysql_query($sqlPost);
		    if(mysql_num_rows($rsPost) > 0){
		    	$rsTotal = mysql_query("SELECT FOUND_ROWS() AS total");
		    	$total = mysql_fetch_array($rsTotal);
		    	$pages = new Paginator;
		    	$pages->items_total = $total['total'];
		    	$pages->mid_range = 3;
		    	$pages->num_pages = ceil($total['total']/PAGING_LIMIT);
		    	$pages->items_per_page = PAGING_LIMIT;
		    	$pages->querystring = true;
		    	$pages->default_ipp = PAGING_LIMIT;
		    	$pages->paginate();
			?>
			<div class="panel panel-default">
				<!-- Default panel contents -->
				<div class="panel-heading"><h4>User list</h4></div>
				<!-- Table -->
				<div class="container-fluid" style="margin:10px 0;">
					<table class="table table-hover table-responsive table-striped tbl-list-post">
					    <tr>
					    	<th>Username</th>
					    	<th>Email</th>
					    	<th>Authorized</th>
					    	<th>Activate</th>
					    	<th>Timezone</th>
					    	<th>Role</th>
					    	<th>Total posts</th>
					    	<th></th>
					    </tr>
					    <?php while($rowUser = mysql_fetch_array($rsPost)): ?>
					    <tr id="user-<?php echo $rowUser['user_id'] ?>">
					    	<td class="user_name"><?php echo $rowUser['user_name'] ?></td>
					    	<td class="user_email"><?php echo $rowUser['user_email'] ?></td>
					    	<td class="user_authorized"><?php echo $rowUser['user_authorized'] ?></td>
					    	<td class="user_activate"><?php echo $rowUser['user_activate'] ?></td>
					    	<td class="user_timezone"><?php echo $rowUser['user_timezone'] ?></td>
					    	<td class="user_role"><?php echo $rowUser['user_role'] ?></td>
					    	<td class="user_role"><?php echo $rowUser['total_pp']+$rowUser['total_gp'] ?></td>
					    	<td align="center">
					    		<a href="javascript:void(0)" class="user-edit" data-id="<?php echo $rowUser['user_id'] ?>" title="Edit user"><span class="glyphicon glyphicon-pencil"> </span></a>
					    		<a href="javascript:void(0)" class="user-remove" data-id="<?php echo $rowUser['user_id'] ?>" title="Remove user"><span class="glyphicon glyphicon-remove"> </span></a>
					    	</td>
					    </tr>
						<?php endwhile; ?>
					</table>
				</div>
			</div>
			<?php if($pages->num_pages > 1): ?>
			<div class="pull-right">
				<ul class="pagination pagination-sm" style="margin: 0;">
					<?php echo $pages->display_pages() ?>
				</ul>
			</div>
			<?php endif; ?>
			<script type="text/javascript">
			$(function(){
				$('.user-edit').click(function(){
					var userId = $(this).attr('data-id');
					var user_role = $('#user-' + userId + ' td.user_role').html(), user_name = $('#user-' + userId + ' td.user_name').html(), user_email = $('#user-' + userId + ' td.user_email').html(), user_timezone = $('#user-' + userId + ' td.user_timezone').html();
					console.log(user_name)
					$('#user_name').val(user_name);
					$('#user_email').val(user_email);
					$('#user_role').val(user_role);
					$('#user_timezone').val(user_timezone);
					$('#user_id').val(userId);
					$('.frm-user h4').html('Update user');
					$('#btn-add').html('<span class="glyphicon glyphicon-pencil"></span> Update user');
					$('#btn-cancel').show();
				});
				$('.user-remove').click(function(){
					if(!confirm('Are you sure want to delete this user?')) return false;
					var userId = $(this).attr('data-id');
					$.ajax({
						url: '<?php echo route('ajax') ?>',
						dataType: 'json',
						type: 'POST',
						data: {act:'delete-user', uid:userId},
						success: function(rs){
							if(rs['success'] == 1){
								$('tr#user-' + userId).fadeOut('fast').remove();
							}
							else if(rs['msg'] != null){
								alert(rs['msg']);
							}
							else{
								alert('Error when deleting user.');
							}
						},
						error: function(xhr, status, err){
							btn.button('reset');
							alert("Error when deleteing user\n" + xhr.responseText);
						}
					});
				});
			});
			</script>
			<?php } ?>
	</div>
	<div class="col-md-5">
			<div class="panel panel-default">
			<!-- Default panel contents -->
			<div class="panel-heading frm-user"><h4>Add new user</h4></div>
			<!-- Table -->
			<div class="container-fluid" style="margin:10px 0;">
				<?php if($msg != ''): ?>
				<div style="margin:0 15px">
					<div class="alert alert-info">
						<?php echo $msg ?>
					</div>
				</div>
				<?php endif; ?>
				<form class="form-horizontal" role="form" method="post">
					<div class="form-group">
					    <label for="user_role" class="col-sm-4 control-label">User role</label>
					    <div class="col-sm-8">
					      <select name="user_role" class="form-control" id="user_role" style="max-width: 400px;">
					      	<option value="USER">USER</option>
					      	<option value="ADMIN">ADMIN</option>
					      </select>
					    </div>
					</div>

					<div class="form-group">
					    <label for="user_name" class="col-sm-4 control-label">User name</label>
					    <div class="col-sm-8">
					      <input type="text" name="user_name" class="form-control" id="user_name" value="">
					    </div>
					</div>
					<div class="form-group">
					    <label for="user_password" class="col-sm-4 control-label">Password</label>
					    <div class="col-sm-8">
					      <input type="password" name="user_password" class="form-control" id="user_password" value="">
					    </div>
					</div>
					<div class="form-group">
					    <label for="repassword" class="col-sm-4 control-label">Re-type password</label>
					    <div class="col-sm-8">
					      <input type="password" name="repassword" class="form-control" id="repassword" value="">
					    </div>
					</div>
					<div class="form-group">
					    <label for="user_email" class="col-sm-4 control-label">Email</label>
					    <div class="col-sm-8">
					      <input type="text" name="user_email" class="form-control" id="user_email" value="">
					    </div>
					</div>
					<div class="form-group">
					    <label for="user_timezone" class="col-sm-4 control-label">Timezone</label>
					    <div class="col-sm-8">
					      <select name="user_timezone" class="form-control" id="user_timezone" style="max-width: 400px;">
					      	<?php echo optTimeZone(); ?>
					      </select>
					    </div>
					</div>
					<div class="form-group">
						<div class="col-sm-offset-4 col-sm-8">
						  <input type="hidden" name="user_id" id="user_id">
						  <a href="<?php echo route('users') ?>"><button type="button" style="display: none;" id="btn-cancel" class="btn btn-default">Cancel</button></a>
						  <button type="submit" id="btn-add" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Add user</button>
						</div>
					</div>
				</form>
			</div>
	</div>
	</div>
</div>
<?php require('footer.php') ?>